<?php
namespace app\index\home;
use app\index\home\Base;
use think\Db;
class User extends Base
{
    protected function initialize()
    {
       parent::initialize();
       
    }

    // 我的——页面基础数据
    // function myData(){
    //     $openid = input('openid/s');
    //     $uid = $this->getUserId($openid);
    //     $jifen = Db::name('user')->where('id',$uid)->value('');
    // }

    // 我的订单列表
    function myOrderList(){
        $page = input('start/d');
		$num = input('limit/d');
        $openid = input('openid/s');
        $serch_type = input('serch_type/d');//搜索类型,1:待付款订单,2:待收货订单,3:待评价订单,4:退换货，5：已完成,0:全部
        $uid = $this->getUserId($openid);
        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 10;
        }
        $star = ($page-1)*$num;
        $time = time();

        // 先查询是否有超时未支付订单，有的话删掉，返还优惠券和积分
        $np_where[] = ['uid','eq',$uid];
        $np_where[] = ['pay_status','eq',0];
        $np_where[] = ['last_pay_time','lt',$time];
        $nopay_orders = Db::name('orders')->where($np_where)->field('id')->select();
        $order_by = 'ctime desc';
        if($nopay_orders){
            foreach($nopay_orders as $kk=>&$vv){
                $id[] = $vv['id'];
            }
            $id_str = implode(',',$id);
            $dwhere[] = ['id','in',$id_str];
            Db::name('orders')->where($dwhere)->delete();
        }

        $where[] = ['uid','eq',$uid];
        // 待付款订单
        if($serch_type==1){
            $where[] = ['pay_status','eq',0];
            $where[] = ['last_pay_time','gt',$time];
            
        }
        // 待发货订单
        elseif($serch_type==2){
            $where[] = ['pay_status','eq',1];
            $where[] = ['is_send','eq',0];
            $where[] = ['sure_return','neq',1];
            
        }
        // 待收货订单
        elseif($serch_type==3){
            $where[] = ['pay_status','eq',1];
            $where[] = ['is_send','eq',1];
            $where[] = ['is_que','eq',0];
            $where[] = ['sure_return','neq',1];
            
        }
        // 退换货
        elseif($serch_type==4){
            $where[] = ['pay_status','eq',1];
            $where[] = ['is_refund','eq',1];
            $order_by = 'apply_time desc';
        }
        // 已完成订单
        elseif($serch_type==5){
            $where[] = ['pay_status','eq',1];
            $where[] = ['is_send','eq',1];
            $where[] = ['is_que','eq',1];
            $where[] = ['sure_return','neq',1];
            
        }
        
        $list = Db::name('orders')->where($where)->order($order_by)->limit($star,$num)->select();
            if($list){
                $data['start'] = $page+1;
                foreach($list as $key=>&$value){
                    $share_img = array();
                    $name = array();
                    $sub_name = array();
                    $value['user_name'] = $value['name'];
                    $goods_ids = $value['goods_id'];
                    $goods_arr = explode(',',$goods_ids);
                    foreach($goods_arr as $k=>&$v){
                        $goods_info = Db::name('product')->where('id',$v)->field('share_img,name,sub_name')->find();
                        $share_img[] = $goods_info['share_img'];
                        $name[] = $goods_info['name'];
                        $sub_name[] = $goods_info['sub_name'];
                    }
                    $value['share_img'] = implode(',',$share_img);
                    $value['name'] = implode(',',$name);
                    $value['sub_name'] = implode(',',$sub_name);

                    $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
                    $value['last_pay_time'] = $value['last_pay_time']-$time;

                    // 判断订单属于什么类型
                    if($value['pay_status']==0){
                        //待支付
                        $value['status'] = 1;
                    }
                    // 用户申请过退款
                    elseif($value['is_refund']==1){
                        if($value['refund_status']==1){
                            $value['status'] = 5;//已完成退款
                        }
                        else{
                            if($value['sure_return']==0){
                                $value['status'] = 6;//买家已申请退款，退款审核中
                            }
                            elseif($value['sure_return']==-1){
                                $value['status'] = 7;//卖家拒绝退货
                            }
                            else{
                                $value['status'] = 8;//卖家同意退货，用户可以上传快递信息
                            }
                        }
                    }
                    elseif($value['is_send']==0){
                        $value['status'] = 2;//待发货
                    }
                    elseif($value['is_send']==1&&$value['is_que']==0){
                        $value['status'] = 3;//待收货
                    }
                    else{
                        $value['status'] = 4;//已完成
                    }
                }
            }
            else{
                $data['start'] = -1;
                $list = array();
            }

            $data['data'] = $list;
            $data['limit'] = $num;
            $data['text'] = '获取成功';
            $data['error'] = 200;
            echo json_encode($data);exit;
    }

    function getUserId($openid){
        // $wxOauth = new Wxoauth();
        // $id = $wxOauth->getUserId();
        // if(!$id){
        //     noLogin();
        // }
        if(!$openid){
            noLogin();
        }
        $id = Db::name('user')->where('openid',$openid)->value('id');
        return $id;
    }

    // 删除待支付订单
    function deleteNopayOrder(){
        $openid = input('openid/s');
        $order_id = input('order_id/d');
        $uid = $this->getUserId($openid);

        $order_check = Db::name('orders')->where(array('id'=>$order_id,'uid'=>$uid))->find();
        if(!$order_check){
            errMsg('无此订单');
        }
        if($order_check['pay_status']==1){
            errMsg('该订单已支付，不能删除');
        }

        // 商城订单
        if($order_check['type']==0){
            if($order_check['quan_id']>0){
                // $quan_info = Db::name('product_quan')->where('id',$order_check['quan_id'])->find();
                Db::name('user_quan')->where(array('id'=>$order_check['quan_id']))->update(array('status'=>0,'use_time'=>0));
            }

            if($order_check['jifen']>0){
                Db::name('user_jifen')->where(array('orders_id'=>$order_check['orders_id']))->delete();
                Db::name('user')->where('id',$uid)->setInc('jifen',$order_check['jifen']);
            }
        }
        // 积分商城订单
        elseif($order_check['type']==1){
            if($order_check['order_jifen']>0){
                Db::name('user_jifen')->where(array('orders_id'=>$order_check['orders_id']))->delete();
                Db::name('user')->where('id',$uid)->setInc('jifen',$order_check['order_jifen']);
            }
        }

        $rs = Db::name('orders')->where('id',$order_id)->delete();

        $res = $this->rebackRestNum($order_check['orders_id']);
        if($rs){
            okMsg('','删除成功');
        }
        else{
            errMsg('删除失败，请联系系统管理员');
        }
    }
    // 我的佣金列表
    function myYongjinList(){
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);
        if(!$openid||!$uid){
            errMsg('参数错误');
        }

        $page = input('start/d');
		$num = input('limit/d');

        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 20;
        }
        $star = ($page-1)*$num;
        $time = time();

        $where[] = ['a.uid','eq',$uid];
        $list = Db::name('user_yongjin')->alias('a')->join('orders b','a.orders_id=b.orders_id','left')->join('user c','b.uid=c.id','left')->where($where)->order('a.ctime desc')->limit($star,$num)->field('a.*,b.goods_id,b.goods_spec,b.goods_num,b.all_goods_price,c.nickname,c.headimg')->select();
        // var_dump(Db::name('user_yongjin')->getLastSql());exit;
        if($list){
            $data['start'] = $page+1;
            foreach($list as &$value){
                if($value['goods_id']){
                    $pwhere[] = ['id','in',$value['goods_id']];
                    $goods_name_arr = Db::name('product')->where($pwhere)->field('name')->select();
                    $goods_names = [];
                    foreach($goods_name_arr as $v){
                        $goods_names[] = $v['name'];
                    }
                    if($goods_names){
                        $goods_name_str = implode(',',$goods_names);
                    }
                    else{
                        $goods_name_str = '';
                    }
                    $value['product_desc'] = "购买了".$goods_name_str."共".$value['all_goods_price'].'元';
                }

                $value['ctime'] = $value['ctime']?date('Y-m-d',$value['ctime']):'';
            }
        }
        else{
            $data['start'] = -1;
            $list = array();
        }

        $data['data'] = $list;
        $data['yongjin_sum'] = Db::name('user')->where('id',$uid)->value('rest_money');
        $data['yongjin_today'] = Db::name('user_yongjin')->where(array('uid'=>$uid,'day'=>date('Y-m-d',$time)))->sum('yongjin');
        $data['limit'] = $num;
        $data['text'] = '获取成功';
        $data['code'] = 200;
        echo json_encode($data);exit;
    }

    // 我的佣金报表
    function myMonthYongjin(){
        $openid = input('openid/s');
        $year = input('year/d');
        $uid = $this->getUserId($openid);
        if(!$year){
            $year = date('Y',time());
        }
        
        for($i=0;$i<=11;$i++){
            $where[] = ['uid','eq',$uid];
            $where[] = ['year','eq',$year];
            $where[] = ['month','eq',$i];
            $rs = Db::name('user_yongjin')->where($where)->sum('yongjin');
            if($rs){
                $data[$i] = $rs;
            }
            else{
                $data[$i] = 0;
            }

            $where = [];
        }
        okMsg($data);
    }

    // 我的积分列表
    function jifenList(){
        $openid = input('openid/s');
        $type = input('type/d');//0：全部，1：收入，2：支出
        $uid = $this->getUserId($openid);
        if(!$openid||!$uid){
            errMsg('参数错误');
        }

        $page = input('start/d');
		$num = input('limit/d');

        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 20;
        }
        $star = ($page-1)*$num;
        $time = time();

        $where[] = ['a.uid','eq',$uid];
        if($type&&$type>0){
            $where[] = ['a.type','eq',$type];
        }
        $list = Db::name('user_jifen')->alias('a')->join('orders b','a.orders_id=b.orders_id','left')->where($where)->order('a.ctime desc')->limit($star,$num)->field('a.*,b.order_price,b.pay_time,b.jifen as jf_use,b.jifen_price,b.type as btype')->select();

        if($list){
            $data['start'] = $page+1;
            foreach($list as &$value){
                $value['pay_time'] = $value['pay_time']?date('Y-m-d',$value['pay_time']):'';
                // 收入积分
                if($value['type']==1){
                    if($value['from_type']==0){
                        $value['describe'] = "消费".$value['order_price']."元";
                        $value['jifen'] = "+".$value['jifen'];
                    }
                    // 分享给别人购买获取积分
                    elseif($value['from_type']==1){
                        $order_info = Db::name('orders')->where('orders_id',$value['orders_id'])->find();
                        $user_name = Db::name('user')->where('id',$order_info['uid'])->value('nickname');
                        // $goods_name = Db::name('product')->where('id',$order_info[''])


                        $pwhere[] = ['id','in',$order_info['goods_id']];
                        $goods_name_arr = Db::name('product')->where($pwhere)->field('name')->select();
                        $goods_names = [];
                        foreach($goods_name_arr as $v){
                            $goods_names[] = $v['name'];
                        }
                        if($goods_names){
                            $goods_name_str = implode(',',$goods_names);
                        }
                        else{
                            $goods_name_str = '';
                        }
                        $value['describe'] = "分享给".$user_name."购买了".$goods_name_str."共".$order_info['order_price'].'元';
                        $value['jifen'] = "+".$value['jifen'];
                    }
                    elseif($value['from_type']==2){
                        $value['describe'] = "商家赠送积分";
                        $value['jifen'] = "+".$value['jifen'];
                    }
                    elseif($value['from_type']==3){
                        $value['describe'] = "订单退款返回积分";
                        $value['jifen'] = "+".$value['jifen'];
                    }
                }
                // 消耗积分
                else{
                    if($value['from_type']==4){
                        $value['describe'] = "订单退款扣除购买商品所得积分";
                        $value['jifen'] = "-".$value['jifen'];
                    }
                    else{
                        if($value['btype']==0){
                            $value['describe'] = "使用".$value['jf_use']."积分抵扣".$value['jifen_price'].'元';
                            $value['jifen'] = "-".$value['jifen'];
                        }
                        else{
                            $value['describe'] = "积分商城购买商品";
                            $value['jifen'] = "-".$value['jifen'];
                        }
                    }
                    
                }
                
            }
        }
        else{
            $list = array();
            $data['start'] = -1;
        }

        $data['data'] = $list;
        $data['jifen_sum'] = Db::name('user')->where('id',$uid)->value('jifen');
        $data['limit'] = $num;
        $data['text'] = '获取成功';
        $data['code'] = 200;
        echo json_encode($data);exit;
    }

    // 常见问题列表
    function q_and_s(){
        $list = Db::name('article_questions')->order('orders asc')->select();
        if(!$list){
            errMsg('暂无数据');
        }
        else{
            foreach($list as &$value){
                if($value['ctime']){
                    $value['ctime'] = date('Y-m-d H:i:s',$value['ctime']);
                }
            }
            okMsg($list);
        }
    }

    // 关于我们
    function about_us(){
        $list = Db::name('articles')->where('id',1)->find();
        if(!$list){
            errMsg('暂无数据');
        }
        else{
            if($list['ctime']){
                $list['ctime'] = date('Y-m-d H:i:s',$list['ctime']);
            }

            if($list['content']){
                $list['content'] = html_entity_decode($list['content']);
            }

            okMsg($list);
        }
    }

    // 确认收货
    function queGetGoods(){
        $orders_id = input('orders_id/s');//产品id
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);
        if(!$orders_id||!$uid){
            errMsg('参数错误');
        }
        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            errMsg('订单不存在');
        }
        if($order_info['uid']!=$uid){
            errMsg('页面错误');
        }

        if($order_info['pay_status']==1&&$order_info['is_send']==1&&$order_info['is_que']==0){
            $up_data['is_que'] = 1;
            $up_data['que_time'] = time();
            $rs = Db::name('orders')->where('orders_id',$orders_id)->update($up_data);
            if($rs){
                // 确认收货，往待评价表里面加上产品信息，等待评价
                $goods_id = $order_info['goods_id'];
                $goods_id_arr = explode(',',$goods_id);
                $goods_id_arr = array_unique($goods_id_arr);
                foreach($goods_id_arr as &$value){
                    $in_data = array(
                        'uid'=>$uid,
                        'pid'=>$value,
                        'oid'=>$order_info['id'],
                    );
                    Db::name('product_consume')->insert($in_data);
                }

                $level = Db::name('config')->where('id',1)->value('level');
                if($level==0){
                    $senddata['miniprogram_state'] = "developer";
                }
                elseif($level==1){
                    $senddata['miniprogram_state'] = "trial";
                }
                else{
                    $senddata['miniprogram_state'] = "formal";
                }
                // 发送订阅消息提示用户
                $senddata['touser']=$openid;
                $senddata['template_id']="SMWR8ZpEpfVLptnROoqHxuzVlwVS-EQVjZHdNvmv8zg";
                $senddata['page'] = "pages/order/order?tab=5";
                // $senddata['miniprogram_state'] = "developer";//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                $senddata['data']=array();
                $senddata['data']['phrase3']=array('value'=>'确认收货');
                $senddata['data']['thing4']=array('value'=>'焕生泉');
                $senddata['data']['amount11']=array('value'=>$order_info['order_price']);
                $senddata['data']['character_string5']=array('value'=>$order_info['orders_id']);
                $senddata['data']['thing9']=array('value'=>'订单已完成，感谢您的购买');

                $access_token = $this->getAccessToken();
                $rs = $this->curlPost('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token,json_encode($senddata),0);
                // file_put_contents('111.txt',$rs);
                
                // 购买的商品是采购送礼商品，上级和购买者都不计算积分
                if($order_info['is_slcg']==1){
                    okMsg('收货成功');
                }
                // 判断用户身份
                $user_info = Db::name('user')->where('id',$order_info['uid'])->find();
                $jifen_bg_time = strtotime("2022-08-05 00:00:00");
                $configs = Db::name('config')->where('id',1)->find();
                if($user_info['level']==0){
                    // 用户是C端用户，判断是否需要返还积分
                    
                    if($configs['jifen_price']>0&&$configs['jifen']>0&&$order_info['order_price']>=$configs['jifen_price']&&$order_info['pay_time']>$jifen_bg_time){
                        // file_put_contents('1.txt',json_encode($configs));
                        $jifen = floor($order_info['order_price']/$configs['jifen_price']*$configs['jifen']);

                        if($jifen>0){
                            // file_put_contents('2.txt',$jifen);
                            Db::name('user')->where('id',$order_info['uid'])->setInc('jifen',$jifen);

                            $jifen_data = array(
                                'uid'=>$order_info['uid'],
                                'orders_id'=>$order_info['orders_id'],
                                'jifen'=>$jifen,
                                'ctime'=>time(),
                                'month'=>date('m',time()),
                                'year'=>date('Y',time()),
                                'day'=>date('Y-m-d',time()),
                                'type'=>1
                            );
                            Db::name('user_jifen')->insert($jifen_data);
                        }
                    }
                }
                else{
                    // 购买用户是内部员工，判断是否需要返还积分
                    if($configs['jifen_price_inner']>0&&$configs['jifen_inner']>0&&$order_info['order_price']>=$configs['jifen_price_inner']&&$order_info['pay_time']>$jifen_bg_time){
                        // file_put_contents('1.txt',json_encode($configs));
                        $jifen = floor($order_info['order_price']/$configs['jifen_price_inner']*$configs['jifen_inner']);

                        if($jifen>0){
                            // file_put_contents('2.txt',$jifen);
                            Db::name('user')->where('id',$order_info['uid'])->setInc('jifen',$jifen);

                            $jifen_data = array(
                                'uid'=>$order_info['uid'],
                                'orders_id'=>$order_info['orders_id'],
                                'jifen'=>$jifen,
                                'ctime'=>time(),
                                'month'=>date('m',time()),
                                'year'=>date('Y',time()),
                                'day'=>date('Y-m-d',time()),
                                'type'=>1,
                                'identify'=>1,
                                'from_type'=>0
                            );
                            Db::name('user_jifen')->insert($jifen_data);
                        }
                    }
                }
                //有上级用户且不是自己分享给自己
                if($order_info['parent_id']>0&&$order_info['parent_id']!=$order_info['uid']){
                    $parent_info = Db::name('user')->where('id',$order_info['parent_id'])->find();

                    if($configs['parent_jifen_price']>0&&$configs['parent_jifen']>0){
                        $jifen = floor($order_info['order_price']/$configs['parent_jifen_price']*$configs['parent_jifen']);

                        $user_identify = Db::name('user')->where('id',$order_info['parent_id'])->value('is_partner');
                        if($jifen>0){
                            // file_put_contents('2.txt',$jifen);
                            Db::name('user')->where('id',$order_info['parent_id'])->setInc('jifen',$jifen);

                            $jifen_data = array(
                                'uid'=>$order_info['parent_id'],
                                'orders_id'=>$order_info['orders_id'],
                                'jifen'=>$jifen,
                                'ctime'=>time(),
                                'month'=>date('m',time()),
                                'year'=>date('Y',time()),
                                'day'=>date('Y-m-d',time()),
                                'type'=>1,
                                'identify'=>$user_identify,
                                'from_type'=>1
                            );
                            Db::name('user_jifen')->insert($jifen_data);
                        }
                    }
                }
            okMsg('收货成功');
            }
            else{
                errMsg('操作失败，请重试');
            }
        }
        else{
            if($order_info['is_que']==1){
                errMsg('已确定收货，请勿重复操作');
            }
            else{
                errMsg('不满足收货条件');
            }
            
        }
    }

    // 物流轨迹查询
    function wuliuCheck(){
        $openid = input('openid/s');
        $orders_id = input('orders_id/s');
        // $openid = '5eYG8fcYRR8FZbFTuCzT9f0';
        // $orders_id = 68;
        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            errMsg('无订单信息');
        }
        if($order_info['pay_status']==0){
            errMsg('订单未支付');
        }
        if($order_info['is_send']==0){
            errMsg('订单未发货');
        }
        $access_token = $this->getAccessToken();
        $data = array(
            'order_id'=>$order_info['orders_id'],
            'openid'=>$openid,
            'delivery_id'=>$order_info['delivery_id'],
            // 'delivery_id'=>'TEST',
            'waybill_id'=>$order_info['waybill_id']
        );
        $url = "https://api.weixin.qq.com/cgi-bin/express/business/path/get?access_token=".$access_token;
        $rs = juhecurl($url,json_encode($data,JSON_UNESCAPED_UNICODE),true);
        if($rs){
            $res = json_decode($rs,true);
            okMsg($res);
        }

    }

    //获取
	function getAccessToken(){
        $token_info = Db::name('access_token')->where('id',1)->find();
        if($token_info['access_token']&&time()-$token_info['ctime']<7000){
            return $token_info['access_token'];
        }
        else
        {	
            $appid=config('APPID');
            $appserct=config('APPSECRET');
            if(empty($appid)||empty($appserct)){
                return false;
            }
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appserct}";
            $getjson=file_get_contents($url);
            $getdata=json_decode($getjson,true);
            $rt=$getdata['access_token'];
            $time = time();
            if(!$token_info){
                $rs = Db::name('access_token')->insert(array('access_token'=>$rt,'ctime'=>$time));
            }
            else{
                $up_data['access_token'] = $rt;
                $up_data['ctime'] = $time;
                $rs = Db::name('access_token')->where('id',1)->update($up_data);
            }
            if($rs){
                return $rt;
            }
            else{
                return false;
            }
            
        }
      
    }

    // 待评论列表
    function consumeList(){
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);
        $where[] = ['a.uid','eq',$uid];
        $where[] = ['a.content','eq',''];
        $list = Db::name('product_consume')->alias('a')->join('product b','a.pid=b.id','left')->where($where)->field('a.*,b.name,b.sub_name,b.share_img')->select();
        if(!$list){
            $list = array();
        }
        okMsg($list);
    }

    // 评论
    function consumeProduct(){
        $openid = input('openid/s');
        // $lid = input('lid/d');//待评论列表的id
        $star = input('star');
        $content = input('content/s');
        $orders_id = input('orders_id/s');
        $pid = input('pid/d');
        $uid = $this->getUserId($openid);

        $oid = Db::name('orders')->where('orders_id',$orders_id)->value('id');
        $up_data = array(
            'star'=>$star,
            'content'=>$content,
            'status'=>0,
            'ctime'=>time()
        );
        $rs = Db::name('product_consume')->where(array('pid'=>$pid,'uid'=>$uid,'oid'=>$oid))->update($up_data);
        if($rs){
            okMsg('评论成功');
        }
        else{
            errMsg('评论失败');
        }

    }

    // 申请退款
    function refundApply(){
        $openid = input('openid/s');
        $orders_id = input('orders_id/s');
        $refund_reason = input('refund_reason/s');
        $uid = $this->getUserId($openid);

        if(!$orders_id||!$uid){
            errMsg('参数错误');
        }

        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            errMsg('无此订单信息');
        }

        if($order_info['pay_status']==0){
            errMsg('此订单未支付，不能申请退款');
        }

        if($order_info['is_refund']==1){
            errMsg('此订单已申请退款，请勿重复操作');
        }

        if($order_info['refund_status']==1){
            errMsg('此订单已退款成功');
        }

        $rs = Db::name('orders')->where('orders_id',$orders_id)->update(array('is_refund'=>1,'refund_reason'=>$refund_reason,'apply_time'=>time(),'sure_return'=>0));
        if($rs){
            okMsg('申请退款成功');
        }
        else{
            errMsg('申请失败，请联系管理员');
        }
    }

    // 退款后填写退单的快递单号和物流信息
    function refundMsg(){
        $openid = input('openid/s');
        $orders_id = input('orders_id/s');
        $kuaidi_name = input('kuaidi_name/s');
        $kuaidi_num = input('kuaidi_num/s');
        $uid = $this->getUserId($openid);

        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            errMsg('无此订单信息');
        }

        $rs = Db::name('orders')->where('orders_id',$orders_id)->update(array('kuaidi_name'=>$kuaidi_name,'kuaidi_num'=>$kuaidi_num,'kuaidi_ctime'=>time()));
        if($rs){
            okMsg('提交成功');
        }
        else{
            errMsg('提交失败，请联系管理员');
        }
    }

    // 根据订单id返回库存
    function rebackRestNum($orders_id){
        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            return false;
        }

        if($order_info['pay_status']==1&&$order_info['is_que']==1){
            return false;
        }

        $goods_id_arr = explode(',',$order_info['goods_id']);
        $goods_spec_arr = explode(',',$order_info['goods_spec']);
        $goods_num_arr = explode(',',$order_info['goods_num']);
        if($order_info['is_slcg']){
            foreach($goods_id_arr as $k=>&$v){
                $goods_info = Db::name('product')->where('id',$v)->field('slcg_spec,slcg_price,spec,rest_num')->find();
                $buy_num = intval($goods_num_arr[$k]);
                // 采购送礼加库存
                if($goods_spec_arr[$k]==$goods_info['slcg_spec']){
                    Db::name('product')->where('id',$v)->setInc('slcg_rest_num',$buy_num);
                    $sell_money = $goods_info['slcg_price']*$buy_num;
                }
                // 普通产品加库存
                else{
                    $goods_all_spec_arr = explode(',',$goods_info['spec']);
                    $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                    foreach($goods_all_spec_arr as $kk=>&$vv){
                        if($vv==$goods_spec_arr[$k]){
                            $goods_rest_num_arr[$kk] += $buy_num;
                        }
                    }
                    $p_rest_num_str = implode(',',$goods_rest_num_arr);
                    Db::name('product')->where('id',$v)->update(array('rest_num'=>$p_rest_num_str));
                    // Db::name('product')->where('id',$v)->setInc('rest_num',$buy_num);
                    // $sell_money = $goods_price_arr[$k]*$buy_num;
                }
                // Db::name('product')->where('id',$v)->setDec('buy_count',$buy_num);

                // $sell_in_data = array(
                //     'gid'=>$v,
                //     'sell_num'=>$goods_num_arr[$k],
                //     'sell_money'=>$sell_money,
                //     'ctime'=>time()
                // );
                // Db::name('product_sell_record')->insert($sell_in_data);
            }
        }
        else{
            foreach($goods_id_arr as $k=>&$v){
                $buy_num = intval($goods_num_arr[$k]);
                $goods_info = Db::name('product')->where('id',$v)->field('slcg_spec,slcg_price,spec,rest_num')->find();
                $goods_all_spec_arr = explode(',',$goods_info['spec']);
                $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                foreach($goods_all_spec_arr as $kk=>&$vv){
                    if($vv==$goods_spec_arr[$k]){
                        $goods_rest_num_arr[$kk] += $buy_num;
                    }
                }
                $p_rest_num_str = implode(',',$goods_rest_num_arr);
                Db::name('product')->where('id',$v)->update(array('rest_num'=>$p_rest_num_str));
                // Db::name('product')->where('id',$v)->setInc('buy_count',$buy_num);
                // $sell_in_data = array(
                //     'gid'=>$v,
                //     'sell_num'=>$goods_num_arr[$k],
                //     'sell_money'=>$goods_price_arr[$k]*$goods_num_arr[$k],
                //     'ctime'=>time()
                // );
                // Db::name('product_sell_record')->insert($sell_in_data);
            }
        }
    }

    function curlPost($url, $data){
		$ch = curl_init();
		$header = array('Content-Type: text/plain');
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		$errorno=curl_errno($ch);
		
		$js=json_decode($tmpInfo,1);
		// echo json_encode($js);exit;
		ob_start();
		var_dump($js);
		var_dump($data);
		file_put_contents('er.txt',ob_get_clean());
		return $js;
		
	}

    // 提交发票信息
    function getFpInfo(){
        $openid = input('openid/s');
        $orders_id = input('orders_id/s');
        $fp_type = input('fp_type/d');
        $fp_title = input('fp_title/s');
        $taxNumber = input('taxNumber/s');
        $companyAddress = input('companyAddress/s');
        $telephone = input('telephone/s');
        $bankName = input('bankName/s');
        $bankAccount = input('bankAccount/s');
        $fapiao_name = input('fapiao_name/s');
        $fapiao_address = input('fapiao_address/s');
        $fapiao_email = input('fapiao_email/s');

        $uid = $this->getUserId($openid);
        $order_info = Db::name('orders')->where(array('uid'=>$uid,'orders_id'=>$orders_id))->find();
        if(!$order_info){
            errMsg('无订单信息');
        }

        if(!$fp_title||!$taxNumber){
            errMsg('请上传发票信息');
        }
        if($order_info['is_refund']==1){
            errMsg('退款订单无法申请发票');
        }
        if($fp_type==2&&(!$fapiao_name||!$fapiao_address||!$telephone)){
            errMsg('选择专票需要填写收件人、地址、电话信息');
        }
        $up_data = array(
            'fp_type'=>$fp_type,
            'fp_title'=>$fp_title,
            'taxNumber'=>$taxNumber,
            'companyAddress'=>$companyAddress,
            'telephone'=>$telephone,
            'bankName'=>$bankName,
            'bankAccount'=>$bankAccount,
            'fapiao_name'=>$fapiao_name,
            'fapiao_address'=>$fapiao_address,
            'fapiao_email'=>$fapiao_email,
        );
        $rs = Db::name('orders')->where('id',$order_info['id'])->update($up_data);
        if($rs){
            okMsg('提交成功');
        }
        else{
            errMsg('提交失败，请重试');
        }
    }
}